import React, { Component } from 'react'
import { SearchOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
    Input,
    Button,
    notification,
    Modal,
    Popover,
    Popconfirm,
    Progress,
    Row,
    Col,
    Tooltip,
    Badge,
    Empty,
} from 'antd';
import styles from '../style.less';
import {getMark, submitMark, resetMark, labelPre, modifyMarkContent,} from '@/services/mark';
import WebSocket from "@/utils/webSocket";
import {getContent} from "@/pages/algorithmModel/mark/components/config";
import TextArea from "antd/es/input/TextArea";

const { confirm } = Modal;
const { Search } = Input;
const colors = ['#ff7100', '#ff9800', '#3bbf45', '#37bc9b', '#1890ff', '#314ed2', '#664be8', '#a94be8', '#e84b9c', '#ee4e53'];

class Classify extends Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSetId: '',// 数据集id
            initTxt: '',
            markId: '',// 当前标注任务的id
            Heights: '',// 列表高度-标签占的高度
            searchTopValue: '', // 头部搜索 关键字
            searchVisible: false, // 是否显示搜索框
            isMarked: false, // 是否已提交
            process: {},//进度
            lables: [], //文本分类
            activeLabel: [], // 已激活的文本分类
          preLabelStatus: 0, // 预标注状态 0 未发起预标注 1 预标注中 2 完成预标注
          usedLabel: false, // 使用了标签的标识 true 使用了标签信息 false 未使用标签信息
          isModify: false, // 修改框的显示
        };
    }

    componentDidMount() {
        const Heights = document.getElementById("contentBox").offsetHeight - document.getElementById("lableBoxs").offsetHeight;
        this.setState({ Heights, markId: this.props.id, }, () => { this.queryTaskInfo() })
    }

    componentWillReceiveProps(nextProps) {
        const { id } = nextProps;
        this.setState({ markId: id }, () => { this.queryTaskInfo() })
    }

    // 获取任务详情
    queryTaskInfo() {
        const { markId } = this.state;
        markId && getMark(markId).then(res => {
            if (res.retCode === '0') {
                const { initTxt, objectLabelList, dataSetId, activeLabel, labelProcess, segmentNum, isMarked,preLabelStatus,usedLabel,id } = res.data;
                this.setState({ preLabelStatus, usedLabel,initTxt, dataSetId, isMarked, lables: objectLabelList, activeLabel: activeLabel || [], process: { labelProcess, segmentNum },labelTextId:id, });
            }
        })
    }

    onSChange = e => {
        this.setState({ searchTopValue: e.target.value.trim() })
    }

    // 文本分类
    chooseLabel(lable) {
        const { activeLabel } = this.state;
        if (activeLabel.includes(lable)) {
            activeLabel.splice(activeLabel.indexOf(lable), 1)
        } else {
            activeLabel.push(lable);
        }
        this.setState({ activeLabel })
    }

    // 重置划词
    onReset() {
        const _this = this;
        confirm({
            title: '确定重置文本分类?',
            okText: '确定',
            cancelText: '取消',
            onOk() {
                const { markId, dataSetId } = _this.state;
                resetMark({ id: markId, dataSetId }).then(res => {
                    if (res.retCode === '0') {
                        notification['success']({
                            message: '操作成功',
                            key: '重置划词',
                            description: '重置文本分类成功',
                        });
                        _this.setState({ activeLabel: [], });
                        _this.props.callBack();
                    }
                })
            }
        });
    }
    // 提交划词
    onSubmit() {
        let _this = this;
        let { markId, initTxt, dataSetId, activeLabel } = _this.state;
        if (activeLabel.length) {
            submits();
        } else {
            confirm({
                title: '你未将文本分类，确定提交?',
                okText: '确定',
                cancelText: '取消',
                onOk() { submits(); }
            });
        }
        function submits() {
            submitMark({ id: markId, dataSetId, activeLabel: activeLabel,isMarked: true }).then(res => {
                if (res.retCode === '0') {
                    notification['success']({
                        message: '操作成功',
                        key: '提交划词',
                        description: '文本分类成功',
                    });
                    _this.queryTaskInfo();
                    _this.props.callBack();
                }
            })
        }
    }

  // 预标注
  onClickLabelPre(){
    const { dataSetId, labelTextId } = this.state;
    const labelTxt = [];
    labelTxt.push({
      labelTextId
    })
    labelPre({ dataSetId, labelTxt }).then(res=>{
      if (res.retCode === '0'){
        notification.success({
          message: '操作成功',
          key: '提交预标注',
          description: '提交预标注成功',
        });
      }
      this.setState({preLabelStatus:1})
    })

      WebSocket('pre_label_task_finish', (res, rws) => {
        if (res.data.id){
            this.queryTaskInfo();
            rws.close();
        }
      }, close => {

      }, error => {

      });

  }

  //修改文本内容
  modifyInitTxt() {
    const { initTxt,preLabelStatus,activeLabel } = this.state;
    if (preLabelStatus !==0 || activeLabel.length !==0) {
      notification.error({
        message: '操作失败',
        key: '编辑失败',
        description: '您已进行标注，如需修改内容，请重置后再行操作',
      });
      return;
    }
    this.setState({ isModify: !this.state.isModify })
  }

  //编辑标注内容
  onTextChange(e) {
    this.setState({ initTxt: e.target.value })
  }

  //提交修改后的标注内容
  onSubmitModify(isMarked) {
    const { markId, initTxt } = this.state;
    modifyMarkContent({
      id: markId,
      initTxt,
      isMarked,
    }).then(res => {
      if (res.retCode === '0') {
        this.setState({ isModify: false })
        this.queryTaskInfo()
        if (isMarked) {
          notification.success({
            message: '操作成功',
            key: '提交修改内容',
            description: '修改内容成功',
          });
          this.queryTaskInfo();
          this.props.callBack();
        }
      }
    })
  }

    render() {
        const { isMarked, initTxt, lables, activeLabel, markId, Heights, searchTopValue, searchVisible, process,preLabelStatus,usedLabel,isModify } = this.state;

        return <>
            <div className={styles.markBoxs}>
                <Row className={styles.actionBoxs}>
                    {markId && <><Col span={17} className={styles.leftAction}>
                        <Progress percent={Number(process.labelProcess) / Number(process.segmentNum) * 100}
                        format={percent => `${Number(process.labelProcess) || 0} / ${Number(process.segmentNum) || 0}`} style={{ width: 240,marginRight:100 }} />
                        <span>请点击文本相关的分类标签(可多选)，选中标签会高亮，已选标签 <strong>{activeLabel.length || 0}</strong> 个</span>
                    </Col>
                        <Col span={7} className={styles.rightAction}>
                          {activeLabel.length !==0 || preLabelStatus !==0 || isMarked ?
                            <Button onClick={this.onReset.bind(this)}>重置</Button> : <Button onClick={this.modifyInitTxt.bind(this)}>{isModify ? '取消' : '编辑'}</Button>
                          }
                          {(preLabelStatus ===0 && usedLabel===false) || (preLabelStatus ===null && usedLabel===null) ?
                            <Button type="primary" onClick={this.onClickLabelPre.bind(this)} style={{marginLeft: 10}}>预标注</Button> :
                            <Button type="primary" style={{marginLeft: 10, opacity: '0.4'}}>预标注</Button>
                          }
                          {isModify ?
                            <Button type="primary" onClick={this.onSubmitModify.bind(this, false)}>提交</Button> :
                            <Button type="primary" onClick={this.onSubmit.bind(this, true)}>{isMarked ? '再次提交' : '提交'}</Button>}
                            <div className={styles.searchLabel}>
                                <div className={styles.rig}>
                                    {!searchVisible && <Tooltip title='搜索' placement="left"><SearchOutlined
                                        onClick={() => { this.setState({ searchVisible: true, searchTopValue: '' }, () => { const { input } = this.inputRef; input.focus(); }) }} /></Tooltip>}
                                </div>
                                {searchVisible && <div className={styles['searcherInput']}>
                                    <Input ref={(input) => { this.inputRef = input; }} placeholder="标签内容" value={searchTopValue} onBlur={() => { this.setState({ searchVisible: false }) }} onChange={this.onSChange.bind(this)} />
                                </div>}
                            </div>
                        </Col></>}
                </Row>
                <div className={styles.lableBoxs} id='lableBoxs'>
                    {
                        markId && lables && lables.map((item, index) => {
                            return (
                                <Button key={index} size={'small'} type="primary" onClick={this.chooseLabel.bind(this, item.labelName)} className={styles[`kg_keyword${index % 10}`]} data-visible={(searchTopValue !== '' && item.labelName.indexOf(searchTopValue) === -1) ? 'none' : null} style={activeLabel.includes(item.labelName) ? { opacity: 1 } : null}>
                                    {item.labelName}
                                </Button>
                            )
                        })
                    }
                </div>
              {
                isModify ?
                  <>
                    <div id={styles.markcontent} style={{height: `${Heights - 168}px`}}>
                      <Form>
                        {initTxt && <TextArea defaultValue={initTxt} autoSize onChange={this.onTextChange.bind(this)}/>}
                      </Form>
                    </div>
                    {/*<Button type="primary" onClick={this.onSubmit.bind(this, false)}>提交</Button>*/}
                  </>
                  :
                  <div id={styles.markcontent} style={{height: `${Heights - 168}px`, fontSize: 16}}>{initTxt}</div>
              }
            </div>
        </>;
    }
}

export default Classify
